package com.llt.controller;

import com.llt.impl.UserServiceImpl;
import com.llt.pojo.User;
import com.llt.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
@Api("用户信息")
@RestController
public class mybatisController {

    @Autowired
    private UserService userService;
    @GetMapping("/getuserlist")
    @ResponseBody
    @ApiOperation("获取所有用户")
    public List<User> getAll(){
        List<User> all = userService.getAll();
        return all;
    }
    @ApiOperation("添加用户")
    @GetMapping("/adduser")
    @ResponseBody
    public int add(User user){
        int i;
        if(user.getUser()==null || user.getPassd()==null){
            return 0;
        }
       return userService.addUser(user);
    }
    @ApiOperation("用户登录")
    @RequestMapping("/login")
    public String login(String name, String password , Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(name, password);
       try {
           //登录没有异常说明可以登录
           subject.login(usernamePasswordToken);
           return "index";
       }catch (UnknownAccountException e){//用户名不纯在
           model.addAttribute("msg","用户名错误");
           return "login";
       }catch (IncorrectCredentialsException e){//用户名不纯在
           model.addAttribute("msg","密码不纯在");
           return "login";
       }
    }
    @ApiOperation("查询用户")
    @RequestMapping("/queryByName")
    @ResponseBody
    public User queryByName(String user){
        User users = userService.queryUserName(user);
        return users;
    }
}
